<template>
  <div>
    <AuthComponent></AuthComponent>
    <div>
      <el-button type="primary" @click="goMyBlog()" style="margin: 0 60px 20px">返回我的博客</el-button>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item>
        <el-button type="primary" @click="save('ruleForm', 1)">保存到草稿箱</el-button>
        <el-button @click="save('ruleForm', 2)">发布</el-button>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="顺序" prop="contentOrder">
        <el-input v-model="ruleForm.contentOrder" type="number"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="cgId">
        <el-select v-model="ruleForm.cgId" placeholder="请选择博客分类">
          <el-option v-for="item in cgArray" :label="item.cgName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权限类型" prop="permissionState">
        <el-radio-group v-model="ruleForm.permissionState">
          <el-radio :label="1" >公开</el-radio>
          <el-radio :label="2" >秘密</el-radio>
        </el-radio-group>
      </el-form-item>
<!--      <el-form-item label="内容" prop="content">-->
<!--        <el-input type="textarea" v-model="ruleForm.content" :autosize="{ minRows: 6, maxRows: 10 }"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="内容" prop="content">
          暂不支持插入图片
          <mavon-editor v-model="ruleForm.content" @change="saveContent" ref=md @imgAdd="$imgAdd" @imgDel="$imgDel"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save('ruleForm', 1)">保存到草稿箱</el-button>
        <el-button @click="save('ruleForm', 2)">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import AuthComponent from "@/components/commen/AuthComponent";

export default {
  name: "BlogSave",
  components: {
    AuthComponent
  },
  data() {
    return {
      img_file: {},
      ruleForm: {
        title: '',
        cgId: '',
        permissionState: '',
        content: '',
        render: '',
        publishState: '',
        contentOrder: ''
      },
      cgArray: [],
      userInfo: {},
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        cgId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        permissionState: [
          { required: true, message: '请选择权限', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.userInfo = this.$store.state.userInfo
    // 查询分类内容
    this.$http.get("/category/person/list?pageNum=0&pageSize=100", {headers: {token: this.userInfo.token}}).then(res => {
      res = res.data
      if (res.code === 0) {
        this.cgArray = res.data.content;
      }
    }).catch(err => {
      console.log(err)
    })

    // 获取到路径上blogId
    let blogId = this.$route.params.blogId
    if (blogId==="undefined") {
      return;
    }
    // 查询博客内容
    this.$http.get("/blog/detail/" + blogId).then(res => {
      res = res.data
      if (res.code === 0) {
        this.ruleForm = res.data;
      }
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    // 绑定@imgAdd event
    $imgAdd(pos, $file){
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append('multipartFile', $file);
      this.$http({
        url: '/oss/upload',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((res) => {
        /**
         * 例如：返回数据为 res = [[pos, url], [pos, url]...]
         * pos 为原图片标志（0）
         * url 为上传后图片的url地址
         */
        console.log(res)
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        $vm.$img2Url(pos, "http://www.baidu.com");
      })
    },
    saveContent(value, render) {
      this.ruleForm.content = value;
      this.ruleForm.render = render;
    },
    goMyBlog() {
      this.$router.push({path: '/blog/person/list'})
    },
    save(formName, state) {
      if (!this.userInfo) {
        this.$message({
          message: '请您先登录, 登录后就能愉快的发布文章了',
          type: 'warning'
        });
        return;
      }
      if (!this.ruleForm.content || !this.ruleForm.render) {
        this.$message({
          message: '请您先保存文章后, 再提交',
          type: 'warning'
        });
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 1.保存 2.发布
          this.ruleForm.publishState = state
          this.$http.post("/blog/save", this.ruleForm, {headers: {token: this.userInfo.token}}).then(res => {
            res = res.data;
            if (res.code === 0) {
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              // 跳转到另一个页面
              let blogId = res.data
              this.$router.push({ path: `/blog/person/list`})
            } else {
              this.$message({
                message: '保存失败',
                type: 'warning'
              });
            }
          }).catch((error) => {
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

</style>